package com.lanchetech.admin.task;

import com.lanchetech.task.AbstractTask;
import com.lanchetech.admin.service.AdvancePaymentService;
import com.lanchetech.bean.vo.AgreementSigningReq;
import com.lanchetech.bean.vo.AgreementSigningVo;
import com.lanchetech.entity.AgreementSigning;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

@Component
public class AgreementSigningTask extends AbstractTask implements CommandLineRunner {

    @Autowired
    private AdvancePaymentService advertisementService;

    private final Map<Long, Future> waitToCommit = new ConcurrentHashMap<>();

    public void addTask(AgreementSigning agreementSigning) {
        if (agreementSigning != null && agreementSigning.getEndTime() != null) {
            ScheduledFuture future = scheduledExecutorService.schedule(() -> {
                advertisementService.closeAgreementSigning(agreementSigning);
                remove(agreementSigning.getId());
                logger.info("close success");
            }, getDelay(agreementSigning.getEndTime()), TimeUnit.MILLISECONDS);
            waitToCommit.put(agreementSigning.getId(), future);
        }
    }

    private void remove(Long id) {
        Future future = waitToCommit.get(id);
        if (future != null && !future.isCancelled()) {
            future.cancel(true);
            waitToCommit.remove(id);
        }
    }

    public long getDelay(Date endTime) {
        long now = System.currentTimeMillis();
        long delay = endTime.getTime() - now;
        if (delay < 0) {
            return 0;
        }
        return delay;
    }


    //    @Order(value = 1)
    public void run(String... args) throws Exception {
        AgreementSigningReq req = new AgreementSigningReq();
        req.setType(1L);
        req.setStatus(2);
        req.setDeleted(false);
        // 找到协议今天结束的数据
        List<AgreementSigningVo> agreementSigningVoList = advertisementService.findAll(req);
        if (CollectionUtils.isNotEmpty(agreementSigningVoList)) {
            agreementSigningVoList.forEach(agreementSigningVo -> addTask(agreementSigningVo));
        }
    }
}
